﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using System.Xml;
using NASA.BeAMartian.Controls;
using System.IO;
using NASA.BeAMartian.Controls.News;
using System.Windows.Navigation;
using Microsoft.TownHall.ServiceClient;

namespace NASA.BeAMartian.Views.Learn
{
    public partial class NewsList : PhoneApplicationPage
    {
        object _selectedItem;
        public THServiceClient client = new THServiceClient();
        private CategoryList Categories = new CategoryList();

        public NewsList()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(NewsList_Loaded);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (NavigationContext.QueryString.ContainsKey("x"))
                pvt.SelectedIndex = int.Parse(this.NavigationContext.QueryString["x"]);
            else pvt.SelectedIndex = 1;

            base.OnNavigatedTo(e);
        }

        private void pvt_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string panel = (e.AddedItems[0] as PivotItem).Tag.ToString();

            if (panel == "Townhall")
            {
                FrameworkElement _root = Application.Current.RootVisual as FrameworkElement;
                ClientState _clientState = (ClientState)_root.DataContext;

                client.CategoriesDownloaded -= new CategoriesDownloadedEventHandler(client_CategoriesDownloaded);
                client.CategoriesDownloaded += new CategoriesDownloadedEventHandler(client_CategoriesDownloaded);
                if (_clientState != null && _clientState.CategoryCache.Categories != null && _clientState.CategoryCache.Categories.Count > 0)
                {
                    Categories = _clientState.CategoryCache.Categories;

                    Dispatcher.BeginInvoke(delegate()
                    {
                        showQuestions();
                        lbTownhall.ItemsSource = Categories;
                    });
                }
                else
                {
                    client.GetCategories();
                }
            }
        }

        void showQuestions()
        {
            pbTownhall.IsIndeterminate = false;
            pbTownhall.Visibility = System.Windows.Visibility.Collapsed;
            (Resources["sbFadeInTownhall"] as Storyboard).Begin();
        }

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            FrameworkElement _root = Application.Current.RootVisual as FrameworkElement;
            ClientState clientState = (ClientState)_root.DataContext;
            if (clientState == null) { clientState = new ClientState(); }
            clientState.CurrentCategory = lbTownhall.SelectedItem as Category;
            _root.DataContext = clientState;

            if (clientState.CurrentCategory != null && !String.IsNullOrEmpty(clientState.CurrentCategory.Slug))
                this.NavigationService.Navigate(new Uri("/Views/Learn/TopicListPage.xaml", UriKind.Relative));
        }

        void client_CategoriesDownloaded(object sender, CategoriesDownloadedEventArgs e)
        {
            try
            {
                Categories = e.Categories;
                Dispatcher.BeginInvoke(delegate()
                {
                    FrameworkElement _root = Application.Current.RootVisual as FrameworkElement;
                    showQuestions();
                    lbTownhall.ItemsSource = Categories;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        void NewsList_Loaded(object sender, RoutedEventArgs e)
        {
            WebClient xmlClient = new WebClient();
            xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xmlClient_DownloadStringCompleted);
            xmlClient.DownloadStringAsync(new Uri("http://mars.jpl.nasa.gov/rss/newsdata.cfm", UriKind.Absolute));
        }

        void xmlClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XmlSerializer x = new XmlSerializer(typeof(NewsItems));

                using (XmlReader reader = XmlReader.Create(new StringReader(e.Result)))
                {
                    lbWhatsNew.ItemsSource = (NewsItems)x.Deserialize(reader);
                }
            }
        }

        private void Image_Loaded(object sender, RoutedEventArgs e)
        {
            Image img = sender as Image;
            img.Source = new BitmapImage(new Uri(string.Format("http://mars.jpl.nasa.gov/images/{0}", img.Tag)));
        }

        private void lbWhatsNew_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0) return;
            NewsItem itm = e.AddedItems[0] as NewsItem;
            this.NavigationService.Navigate(new Uri(String.Format("/Views/Learn/Article.xaml?id={0}", itm.NewsID), UriKind.Relative));
        }

        private void TextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            DateTime dt = DateTime.Parse(tb.Text);
            tb.Text = dt.ToShortDateString();

        }
    }
}
